import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { selectAll } from '../../store/actions'
import TodoItem from '../TodoItem'

// !常（常量 => actionType）爱（Action => 通过 actionCreator 生成 Action）瑞（Reducer => 处理状态）组（组件里面 dispatch action）优秀！

export default function TodoMain() {
  // 持久化的思路
  // 1. 一上来获取数据的时候，本地有，就用本地的，本地没有就从 Redux 里面获取
  // 2. list 变化就存储数据到本地
  const list = useSelector((state) => {
    if (state.filter === 'active') {
      return state.todo.filter((item) => !item.done)
    } else if (state.filter === 'completed') {
      return state.todo.filter((item) => item.done)
    }
    return state.todo
  })
  const dispatch = useDispatch()
  // !确定全选的状态，根据所有的单选的状态来确定
  const isCheckAll = list.every((item) => item.done)
  // !全选操作
  const handleChangeAll = () => dispatch(selectAll(!isCheckAll))
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={isCheckAll}
        onChange={handleChangeAll}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {list.map((item) => (
          <TodoItem key={item.id} item={item} />
        ))}
      </ul>
    </section>
  )
}
